package aptech.lab.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LastModified
 */
@WebServlet("/LastModified")
public class LastModified extends HttpServlet {
	public long getLastModified(HttpServletRequest req) {
        ServletContext context = getServletContext();
        Date timestamp = (Date) context.getAttribute("timestamp");
        if (timestamp == null)
            return -1;
        else
            return timestamp.getTime();
    }

    public void init () {
	    ServletContext context = getServletContext();
	    context.setAttribute("timestamp", new Date());
	    context.setAttribute("counter", new Integer(0));
    }


    public void doGet(HttpServletRequest req, HttpServletResponse res)
                 throws ServletException, IOException {
        res.setContentType ("text/html");
        PrintWriter out = res.getWriter();
        out.println ("<HTML>");
        out.println ("<HEAD><TITLE>Cache Test</TITLE></HEAD>");
        out.println ("<BODY>");

	    ServletContext context = getServletContext();
		String reload = req.getParameter("reload");
		// change the timestamp if paramater reload is true
		if (reload != null && reload.equals("true")) {
		    context.setAttribute("timestamp", new Date());
		}
		// use counter and date to monitor if page updated
		Integer i = (Integer) context.getAttribute("counter");
		int x = i.intValue() + 1;
		context.setAttribute("counter", new Integer(x));
		out.println("<P><b>counter:" + x + "  </b>date:" + new Date() + "</b>");

        out.println ("</BODY>");
        out.println ("</HTML>");
    }

}
